package thirdPartyUtils.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: void
 * @date: 2021-09-10 15:28
 * @description:
 * @version: 1.0
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 客户端与服务端建立连接时执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发送请求至服务端
        System.out.println("channelActive");

        String msg = "{\"invoke_info\":{\"pos_1\":[{}],\"pos_2\":[{}],\"pos_3\":[{}]}}";
        Map<String,String> header = new HashMap<>();
//        header.put("Authorization","Basic NIU3YzE2ZTgxOWU0YjY0MmVjNjg3NWI3OjllOTU2YjdkZmZhNDBhYWU1ZTg4YzVmOQ==");
        String  url ="https://ug.baidu.com/mcp/pc/pcsearch";

        //配置HttpRequest的请求数据和一些配置信息
        HttpRequest request = new ClientHandler().buildRequest(msg,url,true,header);
        ChannelFuture future = ctx.writeAndFlush(request);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                //这里中刷出成功，默认代表已完成发送，不代表成功接受数据
                System.out.println("http netty client刷出数据结果为："+future.isSuccess());
            }
        });

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpResponse response = (FullHttpResponse) msg;
        ByteBuf content = response.content();
        System.out.println(": content:"+content.toString(CharsetUtil.UTF_8));
    }

    public  HttpRequest buildRequest(String msg, String url, boolean isKeepAlive, Map<String,String> headers) throws Exception {
        URL netUrl = new URL(url);
        URI uri = new URI(netUrl.getPath());
        //构建http请求
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                HttpMethod.POST,
                uri.toASCIIString(),
                Unpooled.wrappedBuffer(msg.getBytes(StandardCharsets.UTF_8)));

        //设置请求的host(这里可以是ip,也可以是域名)
        request.headers().set(HttpHeaderNames.HOST, netUrl.getHost());
        //其他头部信息
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.headers().set(entry.getKey(), entry.getValue());
            }
        }
        //设置返回Json
        request.headers().set(HttpHeaderNames.CONTENT_TYPE ,"text/json;charset=UTF-8");
        //发送的长度
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
        //是否是长连接
        if (isKeepAlive){
            request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }

        return request;
    }
}
